<template>
    <h1 v-if="adminId">修改管理员</h1>
    <h1 v-else>添加管理员</h1>
    <el-row>
        <el-form ref="myForm" :rules = "rules" :model="formData">
            <el-form-item prop="adminName" label="用户名">
                <el-input v-model="formData.adminName"></el-input>
            </el-form-item>
            <el-form-item prop="account" label="账号">
                <el-input v-model="formData.account"></el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码">
                <el-input v-model="formData.password"></el-input>
            </el-form-item>
            <el-form-item prop="tel" label="手机号">
                <el-input v-model="formData.tel"></el-input>
            </el-form-item>
            <el-form-item prop="identity" label="标识">
                <el-select v-model="formData.identity" placeholder="请选择标识">
                    <el-option label="管理员" value="0" />
                    <el-option label="商家" value="1" />
                </el-select>
            </el-form-item>
            <el-form-item prop="sex" label="性别">
                <el-radio-group v-model="formData.sex">
                    <el-radio value="0">男</el-radio>
                    <el-radio value="1">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- 图片上传 -->
            <el-form-item label="头像" prop="imageUrl">
                <el-upload
                    class="avatar-uploader"
                    :action="upLoadUrl"
                    name="files"
                    :data="upLoadData"
                    :headers="upLoadHeaders"
                    :show-file-list="false"
                    :on-success="uploadSuccess"
                    :before-upload="beforeAvatarUpload"
                >
                    <img v-if="formData.imageUrl" :src="formData.imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item >
                <el-button type="primary" @click="adminSure(myForm)">确定</el-button>
                <el-button type="danger" @click="adminBack">取消</el-button>
            </el-form-item>
        </el-form>
    </el-row>
</template>
<script setup>
    import { reactive,ref, shallowRef } from 'vue';
    import { ElMessage } from 'element-plus';
    import { Plus } from '@element-plus/icons-vue'
    import { baseUrl } from '@/utlis/RequestPage1';
    import {AddAdmin,UpdateInforAdmin} from "@/api"
    import { useRouter,useRoute } from 'vue-router';
    let router = useRouter();
    let route = useRoute();
    let adminId = shallowRef("");
    adminId.value = route.query.adminId;
    console.log("端粒元的id",adminId.value);
    // 模拟数据
    let formData1 = reactive({
        adminName:"小明",
        account:"222",
        password:"222",
        sex:"0",
        identity:"1",
        tel:"wewqewe",
    })
    let myForm = ref(null);
    let formData = reactive({
        adminName:"",
        account:"",
        password:"",
        sex:"",
        identity:"",
        tel:"",
        imageUrl:""
    })
    let rules = reactive({
        adminName:[
            {required:true,message:"用户名不能为空",trigger:"blur"}
        ],
        account:[
            {required:true,message:"账号不能为空",trigger:"blur"}
        ],
        password:[
            {required:true,message:"密码不能为空",trigger:"blur"}
        ],
        tel:[
            {required:true,message:"电话不能为空",trigger:"blur"}
        ],
        imageUrl:[
            {required:true,message:"图像不能为空",trigger:"change"}
        ],
       
    })
    if(adminId.value){
        // 将模拟数据放页面
        // formData.value = formData1.value;
        Object.assign(formData,formData1)
        console.log(formData.value);
        
    }
    let adminSure = async(fromEl)=>{
        await fromEl.validate(async (valid)=>{
            console.log(valid);
            if(adminId.value){
                // 修改
                // 
                
                var json ={
                    adminId:Number(adminId.value),
                    icon:formData.icon,
                    adminName:formData.adminName,
                    account:formData.account,
                    password:formData.password,
                    sex:formData.sex,
                    tel:formData.tel
                }
                let res  = await UpdateInforAdmin(json);
                ElMessage.success("当前信息修改成功");
                setTimeout(()=>{
                    router.push("/adminIndex/administrators")
                },500)
                 
            }else{
                // 添加管理员
                let json = {
                    adminName:formData.adminName,
                    account:formData.account,
                    password:formData.password,
                    sex:formData.sex,
                    identity:formData.identity,
                    tel:formData.tel,
                    icon:formData.icon
                }
                let res  =await AddAdmin(json);
                ElMessage.success("添加成功");
                // 路由跳转
                router.push({
                    path:"/adminIndex/administrators"
                })
                }
            
        })
    }
    // 点击取消返回上一页
    let adminBack = async()=>{
         // 路由跳转
         router.push({
                path:"/adminIndex/administrators"
            })
    }

    let upLoadHeaders = {token:sessionStorage.getItem("token")};
    let upLoadUrl = baseUrl+"admin/showImages"; // 定义图像地址
    let upLoadData = reactive({path:"/path"});//上传头像的额外参数
    // 上传头像（图片）
    // 上传头像成功时执行
    const uploadSuccess = (response,uploadFile) => {
        console.log("头像的信息",response);
        formData.imageUrl = URL.createObjectURL(uploadFile.raw);
        formData.icon = response.data[0];
    }
    // 上传头像之前对图片格式和大小进行判断
    const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/jpg' ) {
        ElMessage.error('图像格式只能是jpeg/jpg');
        return false
    } else if (rawFile.size / 1024 / 1024 > 4) {
        ElMessage.error('图像不能超过4MB');
        return false
    }
    return true
    }
</script>

<style scoped>
   .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
img{
    width:100px;
    height:100px;
}
</style>